const mysql = require('mysql2/promise');

async function testConnection() {
  console.log('🔍 Testing MySQL connection...');
  console.log('📋 Connection details:');
  console.log('   Host:', '49.51.193.79');
  console.log('   Port:', '3306');
  console.log('   User:', 'prompt');
  console.log('   Database:', 'prompt');
  console.log('   Password:', '***HIDDEN***');
  console.log('');

  const connectionConfig = {
    host: '49.51.193.79',
    port: 3306,
    user: 'prompt',
    password: '42SSH3Br6AH2RsJ2',
    database: 'prompt',
    connectTimeout: 10000,
    acquireTimeout: 10000,
    timeout: 10000
  };

  try {
    console.log('⏳ Attempting to connect...');
    const connection = await mysql.createConnection(connectionConfig);
    
    console.log('✅ Connection successful!');
    
    // Test a simple query
    console.log('🔍 Testing query...');
    const [rows] = await connection.execute('SELECT 1 as test_value, NOW() as current_time');
    console.log('✅ Query successful!');
    console.log('📊 Result:', rows[0]);
    
    // Test database tables
    console.log('🔍 Checking database tables...');
    const [tables] = await connection.execute('SHOW TABLES');
    console.log('📋 Available tables:');
    tables.forEach(table => {
      console.log(`   - ${Object.values(table)[0]}`);
    });
    
    await connection.end();
    console.log('✅ Connection closed successfully!');
    
  } catch (error) {
    console.error('❌ Connection failed:');
    console.error('   Error code:', error.code);
    console.error('   Error message:', error.message);
    console.error('   Error stack:', error.stack);
    
    // Provide specific error guidance
    if (error.code === 'ER_ACCESS_DENIED_ERROR') {
      console.log('');
      console.log('🔧 Access denied error - Possible solutions:');
      console.log('   1. Check username and password');
      console.log('   2. Ensure user has proper permissions');
      console.log('   3. Check if user can connect from this IP');
    } else if (error.code === 'ECONNREFUSED') {
      console.log('');
      console.log('🔧 Connection refused - Possible solutions:');
      console.log('   1. Check if MySQL service is running');
      console.log('   2. Check if port 3306 is open');
      console.log('   3. Check firewall settings');
    } else if (error.code === 'ETIMEDOUT') {
      console.log('');
      console.log('🔧 Connection timeout - Possible solutions:');
      console.log('   1. Check network connectivity');
      console.log('   2. Check if MySQL is accepting remote connections');
      console.log('   3. Check firewall/security group settings');
    }
  }
}

testConnection();